
class AppMainChat {
  constructor() {
    this.messageInput = null;
    this.sendBtn = null;
    this.messageArea = null;
    this.currentModelSpan = null;
    this.ollamaStatusIndicator = null;
    
    // 流式响应相关变量
    this.currentResponseDiv = null;
    this.thinkingContentDiv = null;
    this.typingIndicator = null;
    this.thinkingMessage = null;
    this.newthinkingMessage = null;
    this.newThinkingElement = null;
    this.newthinkingContentDiv = null;
    
    // 全局设置状态
    this.currentSettings = {
      ollama: {
        OLLAMA_BASE_URL: 'http://localhost:11434',
        api: {
          generate: '/api/generate',
          tags: '/api/tags'
        },
        model: 'qwen3:0.6b',
        parameters: {
          temperature: 0.7,
          top_p: 0.9,
          top_k: 40,
          max_length: 2000
        }
      }
    };
  }
  async init() {
    // 加载组件HTML内容
    await this.loadMainChatHTML();
    
    // 获取DOM元素
    this.messageInput = document.getElementById('message-input');
    this.sendBtn = document.getElementById('send-btn');
    this.messageArea = document.getElementById('message-area');
    this.currentModelSpan = document.getElementById('current-model');
    this.ollamaStatusIndicator = document.getElementById('ollama-status');

    // 绑定事件
    this.bindEvents();
    
    // 初始化设置
    this.loadInitialSettings();
    
    // 显示欢迎消息
    this.addMessage('ai', '# 欢迎使用PPM聊天助手\n\n我可以帮助你回答问题，请输入您的问题开始对话。\n\n> 提示: 确保PPM-AI服务已在本地启动，否则无法获取回复。');
    
    // 检查Ollama服务状态
    this.updateOllamaStatus('connecting');
    window.electronAPI.checkOllamaStatus();

  }

  /**
   * 加载主聊天区域HTML内容
   */
  async loadMainChatHTML() {
    try {
      const response = await fetch('./components/app-main-chat.html');
      const mainChatHTML = await response.text();
      
      // 查找现有的主内容区域并替换
      const existingMain = document.querySelector('.app-main-chat');
      if (existingMain) {
        existingMain.outerHTML = mainChatHTML;
      } else {
        // 如果没有现有主内容区域，在header后插入
        const header = document.querySelector('.app-header');
        if (header) {
          header.insertAdjacentHTML('afterend', mainChatHTML);
        } else {
          // 如果没有header，在body中插入
          document.body.insertAdjacentHTML('beforeend', mainChatHTML);
        }
      }
    } catch (error) {
      console.error('加载主聊天区域HTML失败:', error);
    }
  }

  bindEvents() {
    // 监听发送按钮点击事件
    this.sendBtn.addEventListener('click', () => this.sendMessage());

    // 监听回车键
    this.messageInput.addEventListener('keypress', (e) => {
      if (e.key === 'Enter') {
        this.sendMessage();
      }
    });

    // 监听AI处理状态
    window.electronAPI.onAiProcessing((event, isProcessing) => {
      this.handleAiProcessing(isProcessing);
    });

    // 监听AI思考过程
    window.electronAPI.onAiThinking((event, message) => {
      this.handleAiThinking(message);
    });

    // 监听AI思考流
    window.electronAPI.onAiThinkingStream((event, thinkingChunk) => {
      this.handleAiThinkingStream(thinkingChunk);
    });

    // 监听AI流式响应
    window.electronAPI.onAiStreamResponse((event, data) => {
      this.handleAiStreamResponse(data);
    });

    // 监听AI回复 (非流式，保留向后兼容)
    window.electronAPI.onAiResponse((event, response) => {
      this.addMessage('ai', response);
    });

    // 监听Ollama状态
    window.electronAPI.onOllamaStatus((event, status) => {
      this.updateOllamaStatus(status ? 'online' : 'offline');
    });

    // 监听设置更新事件
    document.addEventListener('settingsUpdated', (e) => {
      this.currentSettings = e.detail;
      this.updateCurrentModelDisplay();
    });
  }

  // 发送消息函数
  sendMessage() {
    const message = this.messageInput.value.trim();
    if (message) {
      // 添加用户消息到界面
      this.addMessage('user', message);
      
      // 通过electronAPI发送消息到主进程
      window.electronAPI.sendMessage(message);

      // 清空输入框
      this.messageInput.value = '';
    }
  }

  // 添加消息到界面
  addMessage(sender, text) {
    const messageDiv = document.createElement('div');
    messageDiv.classList.add('message');

    if (sender === 'user') {
      messageDiv.classList.add('user-message');
      messageDiv.textContent = text;
    } else {
      messageDiv.classList.add('ai-message');
      messageDiv.classList.add('markdown-content');
      messageDiv.innerHTML = window.module.marked.parse(text);
    }

    this.messageArea.appendChild(messageDiv);
    // 自动滚动到底部
    this.messageArea.scrollTop = this.messageArea.scrollHeight;

    return messageDiv;
  }

  // 创建"正在输入"的消息元素
  createTypingIndicator() {
    const typingDiv = document.createElement('div');
    typingDiv.id = 'typing-indicator';
    typingDiv.classList.add('message', 'ai-message');
    typingDiv.innerHTML = '<div class="typing-indicator"><span></span><span></span><span></span></div>';
    return typingDiv;
  }

  // 处理AI正在输入状态
  handleAiProcessing(isProcessing) {
    if (isProcessing) {
      // 显示正在输入指示器
      this.typingIndicator = this.createTypingIndicator();
      this.messageArea.appendChild(this.typingIndicator);
      this.messageArea.scrollTop = this.messageArea.scrollHeight;
      // 禁用输入
      this.messageInput.disabled = true;
      this.sendBtn.disabled = true;
    } else {
      // 移除正在输入指示器
      if (this.typingIndicator && this.typingIndicator.parentNode) {
        this.typingIndicator.parentNode.removeChild(this.typingIndicator);
        this.typingIndicator = null;
      }
      // 移除思考中消息
      if (this.thinkingMessage && this.thinkingMessage.parentNode) {
        this.thinkingMessage.parentNode.removeChild(this.thinkingMessage);
        this.thinkingMessage = null;
      }
      // 启用输入
      this.messageInput.disabled = false;
      this.sendBtn.disabled = false;

      // 确保思考内容区域被清理
      this.thinkingContentDiv = null;
    }
  }

  // 处理AI思考状态
  handleAiThinking(message) {
    // 如果message为null，则表示需要隐藏思考消息
    if (message === null) {
      if (this.thinkingMessage && this.thinkingMessage.parentNode) {
        // 不要删除，而是转换为AI响应区域
        this.thinkingMessage.classList.remove('thinking-message');
        this.currentResponseDiv = this.thinkingMessage;
        // 清空内容
        this.currentResponseDiv.innerHTML = '';
        this.thinkingMessage = null;
      }
      return;
    }

    // 如果已经有旧的思考消息，移除它
    if (this.thinkingMessage && this.thinkingMessage.parentNode) {
      this.thinkingMessage.parentNode.removeChild(this.thinkingMessage);
    }

    this.messageArea.scrollTop = this.messageArea.scrollHeight;
  }

  // 处理思考流数据
  handleAiThinkingStream(thinkingChunk) {
    // 如果思考内容区域不存在，创建它
    if (!this.newthinkingContentDiv) {
      this.newthinkingContentDiv = document.createElement('div');
      this.newthinkingContentDiv.classList.add('message', 'ai-message', 'thinking-message');
      this.newthinkingContentDiv.classList.add('thinking-content');
      this.messageArea.appendChild(this.newthinkingContentDiv);
    }

    if (!this.newThinkingElement) {
      this.newThinkingElement = document.createElement('span');
      this.newthinkingContentDiv.appendChild(this.newThinkingElement);
    }

    // 将思考内容添加到思考区域
    if (thinkingChunk.text) {
      this.newThinkingElement.textContent = thinkingChunk.text;
    }

    // 自动滚动到底部
    this.messageArea.scrollTop = this.messageArea.scrollHeight;

    if (thinkingChunk.done) {
      this.newthinkingContentDiv = null;
      this.newThinkingElement = null;
    }
  }

  // 处理流式响应
  handleAiStreamResponse(data) {
    // 如果响应区域不存在，创建它
    if (!this.currentResponseDiv) {
      this.currentResponseDiv = document.createElement('div');
      this.currentResponseDiv.classList.add('message', 'ai-message', 'markdown-content');
      this.messageArea.appendChild(this.currentResponseDiv);
    }

    // 更新响应内容
    if (data.text) {
      // 对增量文本应用Markdown解析
      this.currentResponseDiv.innerHTML = window.module.marked.parse(data.text);
    }

    // 自动滚动到底部
    this.messageArea.scrollTop = this.messageArea.scrollHeight;

    // 如果响应完成，重置当前响应区域
    if (data.done) {
      this.currentResponseDiv = null;
    }
  }

  // 加载初始设置
  loadInitialSettings() {
    try {
      const savedSettings = localStorage.getItem('ollamaSettings');
      if (savedSettings) {
        this.currentSettings = { ...this.currentSettings, ...JSON.parse(savedSettings) };
        this.updateCurrentModelDisplay();
      }
    } catch (error) {
      console.error('加载设置失败:', error);
    }
  }

  // 更新当前模型显示
  updateCurrentModelDisplay() {
    if (this.currentModelSpan) {
      this.currentModelSpan.textContent = this.currentSettings.ollama.model || '未选择';
    }
  }

  // 更新Ollama服务状态指示器
  updateOllamaStatus(status) {
    this.ollamaStatusIndicator.className = 'status-indicator';

    switch (status) {
      case 'online':
        this.ollamaStatusIndicator.classList.add('status-online');
        this.ollamaStatusIndicator.title = 'Ollama服务在线';
        break;
      case 'offline':
        this.ollamaStatusIndicator.classList.add('status-offline');
        this.ollamaStatusIndicator.title = 'Ollama服务离线';
        break;
      case 'connecting':
        this.ollamaStatusIndicator.classList.add('status-connecting');
        this.ollamaStatusIndicator.title = '正在连接Ollama服务...';
        break;
    }
  }

  // 获取当前设置
  getCurrentSettings() {
    return this.currentSettings;  }

  /**
   * 显示聊天组件
   */
  show() {
    const mainElement = document.querySelector('.app-main-chat');
    if (mainElement) {
      mainElement.style.display = 'flex';
    }
  }

  /**
   * 隐藏聊天组件
   */
  hide() {
    const mainElement = document.querySelector('.app-main-chat');
    if (mainElement) {
      mainElement.style.display = 'none';
    }
  }

  // 更新设置
  updateSettings(newSettings) {
    this.currentSettings = { ...this.currentSettings, ...newSettings };
    this.updateCurrentModelDisplay();
  }
}

// 导出组件类
window.AppMainChat = AppMainChat;
